<template>
  <div class="p-2">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <Card>
          <Form ref="queryFormRef" :model="queryParams" layout="inline">
            <FormItem label="编号" name="dataCode">
              <Input v-model:value="queryParams.dataCode" placeholder="请输入编号" allow-clear @pressEnter="handleQuery" />
            </FormItem>
            <FormItem label="表名" name="dataTable">
              <Input v-model:value="queryParams.dataTable" placeholder="请输入表名" allow-clear @pressEnter="handleQuery" />
            </FormItem>
            <FormItem label="表中文名" name="dataTableName">
              <Input v-model:value="queryParams.dataTableName" placeholder="请输入表中文名" allow-clear @pressEnter="handleQuery" />
            </FormItem>
            <!-- <FormItem label="SQL语句" name="dataSql">
              <Input v-model:value="queryParams.dataSql" placeholder="请输入SQL语句" allow-clear @pressEnter="handleQuery" />
            </FormItem>
            <FormItem label="影响因子" name="dataFormula">
              <Input v-model:value="queryParams.dataFormula" placeholder="请输入影响因子" allow-clear @pressEnter="handleQuery" />
            </FormItem> -->
            <FormItem>
              <Button type="primary" @click="handleQuery">搜索</Button>
              <Button @click="resetQuery" style="margin-left: 8px">重置</Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    </transition>

    <Card>
      <template #title>
        <Row :gutter="10" class="mb8" style="margin-bottom: 0">
          <Col :span="1.5">
            <Button type="primary" @click="handleAdd" v-access:code="['data:table:add']">新增</Button>
          </Col>
          <Col :span="1.5">
            <Button type="default" :disabled="single" @click="handleUpdate()" v-access:code="['data:table:edit']">修改</Button>
          </Col>
          <Col :span="1.5">
            <Button danger :disabled="multiple" @click="handleDelete()" v-access:code="['data:table:remove']">删除</Button>
          </Col>
          <Col :span="1.5">
            <Button type="default" @click="handleExport" v-access:code="['data:table:export']">导出</Button>
          </Col>
          <Col :span="1.5" style="margin-left: auto">
            <Button @click="showSearch = !showSearch">{{ showSearch ? '收起' : '展开' }}</Button>
          </Col>
        </Row>
      </template>

      <Table
        :loading="loading"
        :dataSource="tableList"
        :columns="columns"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        row-key="id"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <Space>
              <Tooltip title="修改">
                <Button type="link" size="small" @click="handleUpdate(record)" v-access:code="['data:table:edit']">修改</Button>
              </Tooltip>
              <Tooltip title="删除">
                <!-- <Popconfirm title="确认删除这条记录吗0000？" @confirm="handleDelete(record)">
                  <Button type="link" danger size="small" v-access:code="['data:table:remove']">删除</Button>
                </Popconfirm> -->
                <Button type="link" danger size="small" @click="handleDelete(record)" v-access:code="['data:table:remove']">删除</Button>
              </Tooltip>
            </Space>
          </template>
        </template>
      </Table>

      <Pagination
        v-show="total > 0"
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        show-size-changer
        show-total
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        style="margin-top: 16px; text-align: right"
      />
    </Card>

    <!-- 添加或修改数据对话框 -->
    <Modal
      :title="dialog.title"
      v-model:open="dialog.visible"
      width="500px"
      :confirm-loading="buttonLoading"
      @ok="submitForm"
      @cancel="cancel"
    >
      <Form ref="tableFormRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <FormItem label="编号" name="dataCode">
          <Input v-model:value="form.dataCode" placeholder="请输入编号" />
        </FormItem>
        <FormItem label="表名" name="dataTable">
          <Input v-model:value="form.dataTable" placeholder="请输入表名" />
        </FormItem>
        <FormItem label="表中文名" name="dataTableName">
          <Input v-model:value="form.dataTableName" placeholder="请输入表中文名" />
        </FormItem>
        <FormItem label="SQL语句" name="dataSql">
          <Input.TextArea v-model:value="form.dataSql" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="分组" name="dataGroup">
          <Input.TextArea v-model:value="form.dataGroup" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="排序" name="dataOrder">
          <Input.TextArea v-model:value="form.dataOrder" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="限制" name="dataLimit">
          <Input.TextArea v-model:value="form.dataLimit" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="影响因子" name="dataFormula">
          <Input.TextArea v-model:value="form.dataFormula" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Input.TextArea v-model:value="form.remark" placeholder="请输入内容" :rows="4" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup name="Table" lang="ts">
import { getCurrentInstance, ref, reactive, toRefs, onMounted, nextTick } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import {
  Card,
  Form,
  FormItem,
  Input,
  Button,
  Table,
  Pagination,
  Modal,
  Row,
  Col,
  Space,
  Tooltip,
  Popconfirm,
  message,
} from 'ant-design-vue';
// 图标组件 - 使用 Ant Design Vue 内置图标或移除图标
import { listTable, getTable, delTable, addTable, updateTable } from '#/api/demo/table';
import type { TableVO, TableQuery, TableForm } from '#/api/demo/table/types';
import { downloadExcel } from '#/utils/file/download';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tableList = ref<TableVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const selectedRowKeys = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref();
const tableFormRef = ref();

const dialog = reactive<{ visible: boolean; title: string }>({
  visible: false,
  title: ''
});

const columns = [
  {
    title: '主键ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '编号',
    dataIndex: 'dataCode',
    key: 'dataCode',
    align: 'center',
  },
  {
    title: '表名',
    dataIndex: 'dataTable',
    key: 'dataTable',
    align: 'center',
  },
  {
    title: '表中文名',
    dataIndex: 'dataTableName',
    key: 'dataTableName',
    align: 'center',
  },
  {
    title: 'SQL语句',
    dataIndex: 'dataSql',
    key: 'dataSql',
    align: 'center',
    width: 200,
    ellipsis: true, // 启用省略号
  },
  {
    title: '影响因子',
    dataIndex: 'dataFormula',
    key: 'dataFormula',
    align: 'center',
    width: 200,
    ellipsis: true, // 启用省略号
  },
  {
    title: '分组',
    dataIndex: 'dataGroup',
    key: 'dataGroup',
    align: 'center',
    width: 150,
    ellipsis: true, // 启用省略号
  },
  {
    title: '排序',
    dataIndex: 'dataOrder',
    key: 'dataOrder',
    align: 'center',
    width: 100,
    ellipsis: true, // 启用省略号
  },
  {
    title: '限制',
    dataIndex: 'dataLimit',
    key: 'dataLimit',
    align: 'center',
    width: 100,
    ellipsis: true, // 启用省略号
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 150,
  },
];

const initFormData: TableForm = {
  id: undefined,
  dataCode: undefined,
  dataTable: undefined,
  dataTableName: undefined,
  dataSql: undefined,
  dataFormula: undefined,
  dataGroup: undefined,
  dataOrder: undefined,
  dataLimit: undefined,
  remark: undefined
};

const data = reactive<{
  form: TableForm;
  queryParams: TableQuery & { pageNum: number; pageSize: number };
  rules: Record<string, any[]>;
}>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataCode: undefined,
    dataTable: undefined,
    dataTableName: undefined,
    dataSql: undefined,
    dataFormula: undefined,
    dataGroup: undefined,
    dataOrder: undefined,
    dataLimit: undefined,
    params: {}
  },
  rules: {
    dataCode: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    dataTable: [
      { required: true, message: "表名不能为空", trigger: "blur" }
    ],
    dataTableName: [
      { required: true, message: "表中文名不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTable(queryParams.value);
    tableList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  tableFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const onSelectChange = (keys: Array<string | number>) => {
  selectedRowKeys.value = keys;
  single.value = keys.length !== 1;
  multiple.value = !keys.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加数据";
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TableVO) => {
  reset();
  const _id = row?.id || selectedRowKeys.value[0];
  if (!_id) {
    message.warning('请选择要修改的数据');
    return;
  }
  const res = await getTable(_id);
  // API返回的就是data字段的值，不需要res.data
  Object.assign(form.value, res);
  dialog.visible = true;
  dialog.title = "修改数据";
  // 确保表单数据更新后，使用nextTick等待DOM更新后再设置表单值
  await nextTick();
  tableFormRef.value?.setFieldsValue(form.value);
};

/** 提交按钮 */
const submitForm = async () => {
  try {
    await tableFormRef.value?.validate();
    buttonLoading.value = true;
    if (form.value.id) {
      await updateTable(form.value);
    } else {
      await addTable(form.value);
    }
    message.success("操作成功");
    dialog.visible = false;
    await getList();
  } catch (error) {
    console.error('表单验证失败', error);
  } finally {
    buttonLoading.value = false;
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: TableVO) => {
  const _ids = row?.id || selectedRowKeys.value;
  if (!_ids || (Array.isArray(_ids) && _ids.length === 0)) {
    message.warning('请选择要删除的数据');
    return;
  }
  
  Modal.confirm({
    title: '提示',
    content: `是否确认删除数据编号为"${Array.isArray(_ids) ? _ids.join(',') : _ids}"的数据项？`,
    okType: 'danger',
    onOk: async () => {
      await delTable(_ids);
      message.success("删除成功");
      await getList();
      selectedRowKeys.value = [];
    },
  });
};

/** 导出按钮操作 */
const handleExport = () => {
  downloadExcel('data/table/export', {
    ...queryParams.value
  }, `table_${new Date().getTime()}.xlsx`);
};

/** 分页变化 */
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  getList();
};

/** 分页大小变化 */
const handlePageSizeChange = (_current: number, size: number) => {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
